﻿using OfficeOpenXml;
using System;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
public class CreateItemTable : MonoBehaviour
{
    [SerializeField] private DefaultAsset excelFile;

    private void StartUP()
    {
        if (excelFile != null)
        {
            string path = AssetDatabase.GetAssetPath(excelFile);
            string excelName = excelFile.name;

            FileInfo fileInfo = new FileInfo(path);
            //创建序列化类
            ItemTable itemTable = (ItemTable)ScriptableObject.CreateInstance(typeof(ItemTable));
            //打开Excel文件，using会在使用完毕后自动关闭打开的文件
            using (ExcelPackage excelPackage = new ExcelPackage(fileInfo))
            {
                //表格内的具体表单，我们这里默认是第一张表（从1开始）
                ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets[1];
                //遍历每一行
                int tableCommentsRow = 2;
                for (int i = worksheet.Dimension.Start.Row + tableCommentsRow; i <= worksheet.Dimension.End.Row; i++)
                {
                    ItemTableField levelItem = new ItemTableField();
                    //获取levelItem的type
                    Type type = typeof(ItemTableField);
                    //遍历每一列
                    for (int j = worksheet.Dimension.Start.Column; j <= worksheet.Dimension.End.Column; j++)
                    {
                        //Debug.Log($"数据内容{worksheet.GetValue(i, j)}");

                        //用反射的方法对levelItem进行赋值，worksheet.GetValue{2，j}对应表格和2行j列的内容
                        FieldInfo variable = type.GetField(worksheet.GetValue(2, j).ToString());
                        string tableValue = worksheet.GetValue(i, j).ToString();
                        variable.SetValue(levelItem, Convert.ChangeType(tableValue, variable.FieldType));
                    }
                    //当前行赋值结束，添加到列表中
                    itemTable.ItemTableFieldList.Add(levelItem);
                }
            }

            //保存文件为ScritableObject，并且存储到Assets内
            AssetDatabase.CreateAsset(itemTable, "Assets/Resources/" + excelName + ".asset");
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }

    private void Start()
    {
        StartUP();
    }
}